<template>
  <div class="bg-[white] w-full h-full pt-[40px] px-[40px] text-base flex flex-col">
    <!-- 页面切换标签切换 -->
    <div class="border-b border-gray-200 mb-6">
      <button class="px-4 py-2 mr-2 font-medium border-b-2 transition-all"
        :class="activeTab === 'codingRule' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
        @click="activeTab = 'codingRule'">
        赋码规则
      </button>
      <button class="px-4 py-2 font-medium border-b-2 transition-all"
        :class="activeTab === 'customRule' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
        @click="activeTab = 'customRule'">
        自定义规则
      </button>
    </div>

    <!-- 搜索区域 -->
    <div class="flex flex-wrap justify-start items-center gap-4 mb-6">
      <InputText type="text" label="规则名称" placeholder="请输入规则名称" class="w-[290px]" v-model="searchInfo.name" />
      <Button type="primary" content="查询" @click="handleSearch">
        <template #icon>
          <IconSvg name="search" class="w-[18px] h-[18px]"></IconSvg>
        </template>
      </Button>
      <Button content="重置" @click="resetSearch">
        <template #icon>
          <IconSvg name="refresh" class="w-[15px] h-[15px]"></IconSvg>
        </template>
      </Button>
    </div>

    <!-- 赋码规则页面内容 -->
    <div v-if="activeTab === 'codingRule'" class="flex-1 overflow-auto flex flex-col min-h-0">
      <div class="flex justify-start items-center mb-4">
        <Button type="primary" content="新增" class="mr-[20px]" @click="openAddModel">
          <template #icon>
            <IconSvg name="add" class="w-[18px] h-[18px]"></IconSvg>
          </template>
        </Button>
      </div>

      <DataTable :dataSource="codingRuleData" :columns="codingRuleColumns" class="mt-[20px] flex-1"></DataTable>

      <div class="flex justify-end items-center my-4">
        <label class="font-medium mr-4">共{{ codingPageData.total }}条</label>
        <PaginationBasic :total="codingPageData.total" :page-size="codingPageData.pageSize"
          v-model:current="codingPageData.currentPage" @onPageChange="handlePageChange" />
      </div>
    </div>

    <!-- 自定义规则页面内容 -->
    <div v-if="activeTab === 'customRule'" class="flex-1 overflow-auto flex flex-col min-h-0">
      <div class="flex justify-start items-center mb-4">
        <Button type="primary" content="新增" class="mr-[20px]" @click="openAddModel">
          <template #icon>
            <IconSvg name="add" class="w-[18px] h-[18px]"></IconSvg>
          </template>
        </Button>
      </div>

      <DataTable :dataSource="customRuleData" :columns="customRuleColumns" class="mt-[20px] flex-1"></DataTable>

      <div class="flex justify-end items-center my-4">
        <label class="font-medium mr-4">共{{ customPageData.total }}条</label>
        <PaginationBasic :total="customPageData.total" :page-size="customPageData.pageSize"
          v-model:current="customPageData.currentPage" @onPageChange="handleCustomPageChange" />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <Model :show="showAddModel" @close="showAddModel = false">
      <template #header>
        <h3>{{ currentAddType === 'codingRule' ? '添加赋码规则' : '添加自定义规则' }}</h3>
      </template>
      <template #body>
        <div class="flex flex-col gap-[15px]">
          <!-- 公共字段：规则名称 -->
          <InputText type="text" label="规则名称" placeholder="请输入规则名称" class="w-[360px]" v-model="addInfo.name"
            label-width="60px" />

          <!-- 赋码规则特有字段 -->
          <template v-if="currentAddType === 'codingRule'">
            <InputSelect label="品类型号" class="w-[360px]" v-model="addInfo.modelid">
              <option v-for="item in categoryTypeList" :key="item.value" :value="item.value">{{ item.label }}</option>
            </InputSelect>
            <InputSelect type="text" label="自定义规则" class="w-[360px]" v-model="addInfo.customid" label-width="60px">
              <option v-for="value in customid" :key="value.value" :value="value.value">{{ value.label }}</option>
            </InputSelect>
          </template>

          <!-- 自定义规则特有字段 -->
          <template v-if="currentAddType === 'customRule'">

            <div class="flex items-center">
              <InputText type="text" label="批次码" class="w-[360px]" v-model="ruledesc.datetime"
                :disabled="!batchCodeEnabled" label-width="60px" @input="makeExternalCode" />
              <SwitchButton v-model="batchCodeEnabled" @change="handleBatchCodeChange" class="ml-2" />
            </div>

            <div class="flex items-center">
              <InputText label="随机码" label-width="60px" class="w-[360px]" v-model="ruledesc.random"
                :disabled="!randomCodeEnabled" @input="makeExternalCode" />
              <SwitchButton v-model="randomCodeEnabled" @change="handleRandomCodeChange" class="ml-2" />
            </div>

            <InputText type="text" label="序列号" class="w-[360px]" v-model="ruledesc.number" label-width="60px"
              @input="makeExternalCode" />

            <InputText type="text" label="规则描述" placeholder="序列号" class="w-[360px]" v-model="addInfo.ruledesc"
              label-width="60px" readonly />
          </template>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="取消" @click="handleCancel"></Button>
          <Button type="primary" content="确定" @click="handleConfirm"></Button>
        </div>
      </template>
    </Model>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive } from "vue"
import axios from "../../axios/axios.js"
// 组件导入
import InputText from "../../components/InputText.vue"
import InputSelect from "../../components/InputSelect.vue"
import Button from "../../components/Button.vue"
import IconSvg from "../../components/IconSvg.vue"
import DataTable from "../../components/DataTable.vue"
import Model from "../../components/Model.vue"
import PaginationBasic from "../../components/PaginationBasic.vue"
import Message from "../../components/Message/Message.js"
import SwitchButton from "../../components/SwitchButton.vue"

// 分页数据
const codingPageData = ref({ currentPage: 1, total: 0, pageSize: 10 })
const customPageData = ref({ currentPage: 1, total: 0, pageSize: 10 })

// 数据存储
const codingRuleData = ref([])
const customRuleData = ref([])
const currentAddType = ref('codingRule')
const activeTab = ref('codingRule') // 默认显示赋码规则
const searchInfo = ref({ name: '' })

// 弹窗相关
const showAddModel = ref(false)
const addInfo = ref({})
const operateItem = ref({})
const isAdd = ref(false)

// 开关状态
const batchCodeEnabled = ref(false)
const randomCodeEnabled = ref(false)

// 下拉选择数据
const selectTypeInfo = ref({})
const categoryTypeList = ref({})
const customid = ref({})
const ruledesc = reactive({
  datetime: 'yyyyMMddHHmmss',
  random: 4,
  number: '0001',
})

// 表格列配置
const codingRuleColumns = ref([
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'name', title: '规则名称', dataIndex: 'name', width: 100 },
  { key: 'modelname', title: '使用标识', dataIndex: 'modelname' },
  { key: 'customrulename', title: '使用规则', dataIndex: 'customrulename' },
  { key: 'codetemplate', title: '编码格式', dataIndex: 'codetemplate' },
  { key: 'createTime', title: '创建时间', dataIndex: 'createtime' },
])

const customRuleColumns = ref([
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'name', title: '规则名称', dataIndex: 'name', width: 100 },
  { key: 'rule', title: '规则表达式', dataIndex: 'rule' },
  { key: 'ruledesc', title: '规则描述', dataIndex: 'ruledesc' },
  { key: 'createTime', title: '创建时间', dataIndex: 'createtime' },
])

// 事件处理
const handleBatchCodeChange = (enabled) => {
  if (!enabled) selectTypeInfo.value.categoryFullName = ''
  makeExternalCode()
}

const handleRandomCodeChange = (enabled) => {
  if (!enabled) addInfo.value.encodetypename = ''
  makeExternalCode()
}

const handlePageChange = (page) => {
  codingPageData.value.currentPage = page
  getAllCodingRules()
}

const handleCustomPageChange = (page) => {
  customPageData.value.currentPage = page
  getCustomRules()
}

const openAddModel = () => {
  isAdd.value = true
  showAddModel.value = true
  addInfo.value = {}
  currentAddType.value = activeTab.value
  selectTypeInfo.value = {}
  batchCodeEnabled.value = false
  randomCodeEnabled.value = false
  axios.get("/api/identify/selectall").then(res => {
    if (res.data.Code === "200") {
      categoryTypeList.value = res.data.Data.map(item => ({
        value: item.identifyid,
        label: item.name,
      }))
    }
  })

  // 加载自定义规则
  axios.get("/api/customrule/selectall").then(res => {
    if (res.data.Code === "200") {
      customid.value = res.data.Data.map(item => ({
        value: item.customid,
        label: item.name
      }))
    }
  })
}

const handleCancel = () => {
  isAdd.value = false
  addInfo.value = {}
  showAddModel.value = false
  operateItem.value = {}
}

// 规则生成
const makeRuleString = () => {
  const parts = [];
  if (batchCodeEnabled.value) parts.push(`[datetime|${ruledesc.datetime}]`);
  if (randomCodeEnabled.value) parts.push(`[random|${ruledesc.random}]`);
  parts.push(`[number|${ruledesc.number}]`);
  return parts.join('.');
};

const makeExternalCode = () => {
  const parts = []
  if (batchCodeEnabled.value && ruledesc.datetime) parts.push('批次码')
  if (randomCodeEnabled.value && ruledesc.number) parts.push('随机码')
  parts.push('序列号')
  addInfo.value.ruledesc = parts.join(' . ')
  addInfo.value.rule = makeRuleString()
}

// 数据请求
const getAllCodingRules = () => {
  let url = `/api/codingrule/select?pageNum=${codingPageData.value.currentPage}&pageSize=${codingPageData.value.pageSize}`
  if (searchInfo.value.name) url += `&name=${searchInfo.value.name}`

  axios.get(url)
    .then(res => {
      if (res.data.Code === "200") {
        codingRuleData.value = res.data.Data.records || []
        codingPageData.value = {
          currentPage: res.data.Data.current || 1,
          total: res.data.Data.total || 0,
          pageSize: res.data.Data.size || 10,
        }
      } else {
        Message.warn(res.data.Msg || "获取赋码规则失败")
        codingRuleData.value = []
        codingPageData.value.total = 0
      }
    })
    .catch(err => {
      Message.error("网络错误，无法获取赋码规则")
      console.error("赋码规则查询失败：", err)
    })
}

const getCustomRules = () => {
  let url = `/api/customrule/select?pageNum=${customPageData.value.currentPage}&pageSize=${customPageData.value.pageSize}`
  if (searchInfo.value.name) url += `&name=${searchInfo.value.name}`

  axios.get(url)
    .then(res => {
      if (res.data.Code === "200") {
        customRuleData.value = res.data.Data.records || []
        customPageData.value = {
          currentPage: res.data.Data.current || 1,
          total: res.data.Data.total || 0,
          pageSize: res.data.Data.size || 10,
        }
      } else {
        Message.warn(res.data.Msg || "获取自定义规则失败")
        customRuleData.value = []
        customPageData.value.total = 0
      }
    })
    .catch(err => {
      Message.error("网络错误，无法获取自定义规则")
      console.error("自定义规则查询失败：", err)
    })
}

const handleConfirm = () => {
  // 公共验证
  if (!addInfo.value.name?.trim()) {
    Message.warn('请输入规则名称')
    return
  }

  if (currentAddType.value === 'customRule') {
    // 自定义规则提交
    const ruleString = makeRuleString()
    // if (!addInfo.value.type) {
    //   Message.warn('请选择分类')
    //   return
    // }
    if (!ruledesc.number) {
      Message.warn('请输入序列号')
      return
    }

    axios.post("/api/customrule/save ", {
      "name": addInfo.value.name,
      "rule": ruleString,
      "ruledesc": addInfo.value.ruledesc,
    }).then(res => {

      if (res.data.Code === "200") {
        Message.success('自定义规则添加成功')
        showAddModel.value = false
        getCustomRules()
      } else {
        Message.warn(res.data.Msg)
      }
    }).catch(() => Message.error('添加失败，请重试'))
  } else {
    // 赋码规则提交
    if (!addInfo.value.modelid) {
      Message.warn('选择品类型号')
      return
    }
    if (!addInfo.value.customid) {
      Message.warn('请选择自定义规则')
      return
    }

    axios.post("/api/codingrule/save", {
      "name": addInfo.value.name,
      "modelid": addInfo.value.modelid,
      "customruleid": addInfo.value.customid,
    }).then(res => {
      if (res.data.Code === "200") {
        Message.success('赋码规则添加成功')
        showAddModel.value = false
        getAllCodingRules()
      } else {
        Message.warn(res.data.Msg)
      }
    }).catch(() => Message.error('添加失败，请重试'))
  }
}

// 搜索与重置
const handleSearch = () => {
  if (activeTab.value === 'codingRule') {
    codingPageData.value.currentPage = 1
    getAllCodingRules()
  } else {
    customPageData.value.currentPage = 1
    getCustomRules()
  }
}

const resetSearch = () => {
  searchInfo.value = { name: '' }
  if (activeTab.value === 'codingRule') {
    codingPageData.value.currentPage = 1
    getAllCodingRules()
  } else {
    customPageData.value.currentPage = 1
    getCustomRules()
  }
}

// 生命周期
watch(() => activeTab.value, (newTab) => {
  newTab === "codingRule" ? getAllCodingRules() : getCustomRules()
})

onMounted(() => {

  // 加载初始数据
  activeTab.value === "codingRule" ? getAllCodingRules() : getCustomRules()
})
</script>

<style scoped>
.primary {
  color: #165DFF;
  border-color: #165DFF;
}
</style>